package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.to.MemberRespVo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.feign.ThirdPartFeignService;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegistVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author wfjytd
 * @create 2022-01-03 17:46
 */
@Controller
public class LoginController {
    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    ThirdPartFeignService thirdPartFeignService;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * //TODO 重定向携带数据，利用session原理，将数据放在session中，
     * 只要跳转到下一个页面取出这个数据，session中的数据就会删掉
     * //TODO分布式下 session 的问题
     * RedirectAttributes redirectAttributes 重定向携带数据
     * redirectAttributes.addFlashAttribute("errors", errors); 只能取一次
     *
     * @param vo                 数据传输对象
     * @param result             用于验证参数
     * @param redirectAttributes 数据重定向
     * @return
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult result,
                         RedirectAttributes redirectAttributes) {
        // 校验是否通过
        if (result.hasErrors()) {
            // 拿到错误信息转换成Map
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            //用一次的属性
            redirectAttributes.addFlashAttribute("errors", errors);
            // 校验出错，转发到注册页
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        // 将传递过来的验证码 与 存redis中的验证码进行比较
        String code = vo.getCode();
        String s = (String) redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (!StringUtils.isEmpty(s)) {
            // 验证码和redis中的一致
            if (code.equals(s.split("_")[0])) {
                // 删除验证码：令牌机制
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                // 调用远程服务，真正注册
                R r = memberFeignService.regist(vo);
                if (r.getCode() == 0) {
                    // 远程调用注册服务成功
                    return "redirect:http://auth.gulimall.com/login.html";
                } else {
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", r.getData(new TypeReference<String>() {
                    }));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            } else {
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("code", "验证码错误");
                // 校验出错，转发到注册页
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        } else {

            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("code", "验证码错误");
            // 校验出错，转发到注册页
            return "redirect:http://auth.gulimall.com/reg.html";

        }
    }
    @PostMapping("/regist1")
    public String regist1(@Valid UserRegistVo vo, BindingResult result,
                          RedirectAttributes redirectAttributes){
        // 校验是否通过
        if (result.hasErrors()){
            Map<String,String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField,FieldError::getDefaultMessage));
            redirectAttributes.addAttribute("error",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        // 将传递过来的验证码 与 存redis中的验证码进行比较
        String code = vo.getCode();
        String s = (String) redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (!StringUtils.isEmpty(s)){
            if (code.equals(s.split("_")[0])){
                // 删除验证码：令牌机制
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                // 调用远程服务，真正注册
                R r = memberFeignService.regist(vo);
                if (r.getCode() ==0){
                    // 远程调用注册服务成功
                    return "redirect:http://auth.gulimall.com/login.html";
                }else {
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", r.getData(new TypeReference<String>() {
                    }));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }

            }else {
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("code", "验证码错误");
                // 校验出错，转发到注册页
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        }else {
            Map<String,String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            redirectAttributes.addAttribute("error",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }


    }





    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null) {
            return "login";

        } else {
            return "redirect:http://gulimall.com";
        }
    }

    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session) {
        //远程登录
        R login = memberFeignService.login(vo);
        if (login.getCode() == 0) {
            MemberRespVo data = login.getData("data", new TypeReference<MemberRespVo>() {
            });
            session.setAttribute("loginUser", data);
            return "redirect:http://gulimall.com";
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", login.getData("msg", new TypeReference<String>() {
            }));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }

    }


    /**
     * 发送短信验证码
     *
     * @param phone 手机号
     * @return
     */
//    @GetMapping("/sms/sendCode")
//    @ResponseBody
//    public R sendCode(@RequestParam("phone") String phone) {
//        // TODO 1、接口防刷
//        // 先从redis中拿取
//        String redisCode = (String) redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
//        if (!StringUtils.isEmpty(redisCode)) {
//            // 拆分
//            long l = Long.parseLong(redisCode.split("_")[1]);
//            // 当前系统事件减去之前验证码存入的事件 小于60000毫秒=60秒
//            if (System.currentTimeMillis() - l < 60000) {
//                // 60秒内不能再发
//                R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
//            }
//        }
//        // 2、验证码的再次效验
//        // 数据存入 =》redis key-phone value - code sms:code:131xxxxx - >45678
//        String code = UUID.randomUUID().toString().substring(0, 5).toUpperCase();
//        // 拼接验证码
//        String substring = code + "_" + System.currentTimeMillis();
//        // redis缓存验证码 防止同一个phone在60秒内发出多次验证吗
//        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, substring, 10, TimeUnit.MINUTES);
//
//        // 调用第三方服务发送验证码
//        thirdPartFeignService.sendCode(phone, code);
//        return R.ok();
//    }

    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone){
        String redisCode = (String) redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)){
            //拆分
            long l = Long.parseLong(redisCode.split("_")[1]);
            //当前系统事件减去之前验证码存入的事件 小于60000毫秒=60秒
            if (System.currentTimeMillis() - l <60000){
                //60秒内不能再次发送
                R.error(300,"时间太短，不能再次发送");
            }

        }

        //2.验证码再次校验
        String code = UUID.randomUUID().toString().substring(0, 5).toUpperCase();
        String substring = code + "_" + System.currentTimeMillis();
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX,substring);
        thirdPartFeignService.sendCode(phone, code);
        return R.ok();
    }





}
